package controllers

import (
	"acs/management/models"
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"strconv"

	"github.com/labstack/echo"
)

type uploadResponseRawPath struct {
	Raw string `json:"raw"`
}
type uploadResonseStruct struct {
	Code    int                   `json:"code"`
	Info    string                `json:"info,omitempty"`
	RawPath uploadResponseRawPath `json:"paths,omitempty"`
}

func PatchUpload(c echo.Context) error {
	defer models.ErrorHandler(c)
	result, err := receiveAndUploadPatch(c)
	c.JSON(http.StatusOK, result)
	return err
}
func receiveAndUploadPatch(c echo.Context) (map[string]string, error) {
	result := make(map[string]string)
	appIdStr := c.FormValue("appid")
	appId, err := strconv.Atoi(appIdStr)
	if err != nil {
		return result, err
	}
	currentapp, err := models.GetTAppById(int64(appId))
	if err != nil {
		return result, err
	}
	if currentapp.Enable == 0 {
		return result, errors.New("此app已经不可用")
	}
	patchFile, err := c.FormFile("patchFile")
	if err != nil {
		return result, err
	}

	paraMap := make(map[string]string)
	paraMap["fileName"] = patchFile.Filename
	paraMap["password"] = models.Conf.JumeiPicsystem.Jumei_picsystem_pswd
	paraMap["path"] = models.Conf.JumeiPicsystem.Jumei_picsystem_path + "/" + appIdStr
	paraMap["user"] = models.Conf.JumeiPicsystem.Jumei_picsystem_name
	paraMapJson, mapErr := json.Marshal(paraMap)
	if mapErr != nil {
		return result, mapErr
	}
	src, err := patchFile.Open()
	defer src.Close()
	if err != nil {
		return result, err
	}
	fd, fderr := ioutil.ReadAll(src)
	if fderr != nil {
		return result, fderr
	}
	body := new(bytes.Buffer)
	w := multipart.NewWriter(body)
	w.WriteField("configfile", string(paraMapJson))
	file, err := w.CreateFormFile("imagefile", patchFile.Filename)
	if err != nil {
		return result, err
	}
	file.Write(fd)
	w.Close()
	request, requesterr := http.NewRequest(http.MethodPost, models.Conf.JumeiPicsystem.Jumei_picsystem_host, body)
	request.Header.Set("Content-Type", "multipart/form-data; boundary="+w.Boundary())
	if requesterr != nil {
		return result, requesterr
	}
	client := new(http.Client)
	respo, respoErr := client.Do(request)
	if respoErr != nil {
		return result, respoErr
	}
	responBody, RespBodeyErr := ioutil.ReadAll(respo.Body)
	if RespBodeyErr != nil {
		return result, RespBodeyErr
	}
	defer respo.Body.Close()
	var uploadResonse uploadResonseStruct
	json.Unmarshal(responBody, &uploadResonse)
	if uploadResonse.Code != 1000 {

		return result, errors.New(uploadResonse.Info)
	}
	//	_ = appId
	// currentUser := models.CheckLogin(c)
	// _, err = models.CheckUserPrivilege(&currentUser, models.TableApp, appId, models.RoleUpdate)
	// models.CheckError(err)
	md5h := md5.New()
	_, err = io.Copy(md5h, bytes.NewReader(fd))
	if err != nil {
		return result, err
	}
	// models.AppendLog(&currentUser, "上传补丁"+patchFile.Filename, models.LOG_TYPE_PATCH)

	result["url"] = uploadResonse.RawPath.Raw
	result["md5"] = hex.EncodeToString(md5h.Sum(nil))
	result["size"] = strconv.Itoa(len(fd))

	return result, err
}

// func FileUpload2Local(c echo.Context) error {
// 	defer models.ErrorHandler(c)
// 	appIdStr := c.FormValue("appid")
// 	appId, err := strconv.Atoi(appIdStr)
// 	models.CheckError(err)
// 	file, err := c.FormFile("createPatch_patch_url")
// 	models.CheckError(err)
// 	src, err := file.Open()
// 	models.CheckError(err)
// 	defer src.Close()
// 	currentUser := models.CheckLogin(c)
// 	_, err = models.CheckUserPrivilege(&currentUser, models.TableApp, appId, models.RoleUpdate)
// 	models.CheckError(err)
// 	filePath := models.Conf.PatchDir + "/" + appIdStr + "/"
// 	newfilename := filePath + file.Filename
// 	existFile, existerr := os.Open(newfilename)
// 	defer existFile.Close()
// 	if existerr == nil && existFile != nil {
// 		models.CheckError(errors.New("该名称的补丁已经存在，请检查"))
// 	}
// 	direrr := os.MkdirAll(filePath, 0666)
// 	models.CheckError(direrr)
// 	dst, err := os.Create(newfilename)
// 	models.CheckError(err)
// 	defer dst.Close()
// 	// Copy
// 	_, err = io.Copy(dst, src)
// 	models.CheckError(err)
// 	fileheader, iderr := os.Open(newfilename)
// 	defer fileheader.Close()
// 	models.CheckError(iderr)
// 	md5h := md5.New()
// 	_, err = io.Copy(md5h, fileheader)
// 	models.CheckError(iderr)
// 	models.AppendLog(&currentUser, "上传补丁"+newfilename, models.LOG_TYPE_PATCH)
// 	result := make(map[string]interface{})
// 	result["url"] = newfilename
// 	result["md5"] = hex.EncodeToString(md5h.Sum(nil))
// 	fileState, _ := fileheader.Stat()
// 	result["size"] = fileState.Size()
// 	c.JSON(http.StatusOK, result)
// 	return nil
// 	//	return c.HTML(http.StatusOK, fmt.Sprintf("<p>File %s uploaded successfully  </p>", file.Filename))
// }
